<script setup>
import { onMounted, ref } from "vue";
import { ArrowDown } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { commodityDetailService } from "@/api/commodity";
import { addCartService } from "@/api/cart";
import bwPowerSet from "@/components/power-set";
import { useUserInfoStore } from "@/stores/userInfo.js";
import "@/assets/style/config.scss";

const userInfoStore = useUserInfoStore();
console.log(userInfoStore.address);
const router = useRouter();

onMounted(() => {
  getdetail();
});

// 商品参数数据模型
const detail = ref({
  commodity: {
    commodityId: 0,
    categoryId: 0,
    commodityTitle: "",
    commodityPrice: 0,
  },
  specs: [
    {
      commodityId: "",
      name: "",
      values: [
        {
          name: "",
        },
        {
          name: "",
        },
      ],
    },
  ],
  skus: [
    {
      skuId: "",
      commodityId: "",
      specs: [
        {
          name: "",
          valueName: "",
        },
      ],
      price: 0,
      stock: 0,
    },
  ],
  images: [],
});

// 商品数量
const count = ref(1);

// 用户选择的商品sku对象
let sku = {};

//
let pathMap = {};

// 获取商品参数和属性数据
const getdetail = async () => {
  //route商品id
  const route = useRoute();
  const commodityId = route.params.id;
  let result = await commodityDetailService(commodityId);
  console.log(result);
  detail.value = result.data;
  pathMap = getPathMap(detail.value);
  initDisabled(detail.value.specs, pathMap);
};

// 切换选中状态
const checkSelected = (param, data) => {
  if (data.disabled) return;
  // param 一行
  // data 一行中的数据
  if (data.selected) {
    data.selected = false;
  } else {
    param.values.forEach((data) => (data.selected = false));
    data.selected = true;
  }
  // 点击按钮时更新禁用状态
  updateDisabled(detail.value.specs, pathMap);
  // 产出sku
  const index = getSelectedValues(detail.value.specs).findIndex(
    (item) => item === undefined
  );
  if (index < 0) {
    // 获取sku对象
    const key = getSelectedValues(detail.value.specs).join("-");
    const skuIds = pathMap[key];
    // 以skuid为key，获取sku对象
    sku = detail.value.skus.find((item) => item.skuId === skuIds[0]);
    totalAmount.value = sku.price * count.value;
    return;
  }
  // 取消选中清空sku
  sku = {};
  count.value = 1;
};

// 生成有效路径字典对象
const getPathMap = (detail) => {
  const pathMap = {};
  // 生成有效sku数组
  const effectiveSkus = detail.skus.filter((sku) => sku.stock > 0);
  // 根据有效的sku使用算法（子集算法）
  effectiveSkus.forEach((sku) => {
    // 获得匹配的valueName数组
    const selectedValArr = sku.specs.map((val) => val.valueName);
    // 使用算法获得子集
    const valueArrPowerSet = bwPowerSet(selectedValArr);
    // 把得到子集生成最终的路径字典对象
    valueArrPowerSet.forEach((arr) => {
      const key = arr.join("-");
      // 如果已经存在当前key了，就往数组中添加skuid，如果不存在key直接做赋值
      if (pathMap[key]) {
        pathMap[key].push(sku.skuId);
      } else {
        pathMap[key] = [sku.skuId];
      }
    });
  });
  return pathMap;
};

// 初始化禁用状态
const initDisabled = (specs, pathMap) => {
  specs.forEach((spec) => {
    spec.values.forEach((val) => {
      if (pathMap[val.name]) {
        val.disabled = false;
      } else {
        val.disabled = true;
      }
    });
  });
};

// 获取选中项的匹配数组
const getSelectedValues = (specs) => {
  const arr = [];
  specs.forEach((spec) => {
    const selectedVal = spec.values.find((item) => item.selected);
    arr.push(selectedVal ? selectedVal.name : undefined);
  });
  return arr;
};

// 点击时切换更新状态
const updateDisabled = (specs, pathMap) => {
  specs.forEach((spec, index) => {
    const selectedVal = getSelectedValues(specs);
    spec.values.forEach((val) => {
      selectedVal[index] = val.name;
      const key = selectedVal.filter((value) => value).join("-");
      if (pathMap[key]) {
        val.disabled = false;
      } else {
        val.disabled = true;
      }
    });
  });
};

// 商品总金额
const totalAmount = ref(0);
// 商品数量变化
const changeCount = () => {
  if (count.value < 1) {
    ElMessage.error("商品数量不能小于1");
    count.value = 1;
    return;
  } else if (count.value > sku.stock) {
    ElMessage.error("商品库存不足");
    count.value = sku.stock;
    return;
  } else if (Object.keys(sku).length === 0) {
    ElMessage.error("请选择商品规格");
    count.value = 1;
    return;
  }
  totalAmount.value = sku.price * count.value;
};

// 加入购物车
const addCart = async () => {
  if (Object.keys(sku).length === 0) {
    ElMessage.error("请选择商品规格");
    return;
  }
  const param = {
    commodityId: detail.value.commodity.commodityId,
    skuId: sku.skuId,
    cartQuantity: count.value,
  };
  let res = await addCartService(param);
  ElMessage.success(res.message);
};

// 立即购买
const buy = () => {
  if (Object.keys(sku).length === 0) {
    ElMessage.error("请选择商品规格");
    return;
  }
  let orderCommodity = [
    {
      commodity: detail.value.commodity,
      sku: sku,
      quantity: count.value,
      totalPrice: sku.price * count.value,
    },
  ];
  console.log(orderCommodity);
  router.push({
    path: `/confirm`,
    query: {
      commodityConfirm: JSON.stringify(orderCommodity),
    },
  });
  console.log(detail.value);
};
</script>

<template>
  <el-main class="main-container">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-carousel height="500px" class="main-container-carousel">
          <el-carousel-item v-for="url in detail.images" :key="url.id">
            <img :src="url" class="main-container-carousel-img" />
          </el-carousel-item>
        </el-carousel>
      </el-col>
      <!-- 商品信息 -->
      <el-col :span="12">
        <el-row>
          <el-col :span="24">
            <!-- 商品标题 -->
            <div class="main-container-title">
              {{ detail.commodity.commodityTitle }}
            </div>
          </el-col>
          <el-col :span="24">
            <!-- 商品价格 -->
            <div v-if="totalAmount === 0" class="main-container-price">
              {{ detail.commodity.commodityPrice }}￥
            </div>
            <div v-else class="main-container-price">{{ totalAmount }} ￥</div>
          </el-col>
          <table class="main-container-table">
            <tbody>
              <!-- 商品参数 -->
              <tr v-for="(value, key) in detail.specs" :key="key">
                <!-- 商品参数名称 -->
                <td style="white-space: nowrap">{{ value.name }}：</td>
                <!-- 商品参数数据 -->
                <td>
                  <button
                    v-for="(item, index) in value.values"
                    :key="index"
                    :class="{
                      selected: item.selected,
                      disabled: item.disabled,
                    }"
                    @click="($event) => checkSelected(value, item)"
                    plain
                  >
                    {{ item.name }}
                  </button>
                </td>
              </tr>
              <tr>
                <!-- 商品数量 -->
                <td>数量：</td>
                <td>
                  <el-input-number v-model="count" @change="changeCount" />
                </td>
              </tr>
            </tbody>
          </table>
          <el-button class="cart-btn" type="primary" plain @click="buy()"
            >立即购买</el-button
          >
          <el-button class="cart-btn" type="primary" plain @click="addCart()"
            >加入购物车</el-button
          >
        </el-row>
      </el-col>
    </el-row>
  </el-main>
</template>

<style scoped lang="scss">
// lang = "scss" 中需要导入外部的qss文件（全局变量）
@import "@/assets/style/config.scss";

@mixin sku-state-mixin {
  &.selected {
    border: 1px solid;
    border-color: $themeColor;
    background-color: $themeColor;
    color: white;
  }

  &.disabled {
    opacity: 0.6;
    border-style: dashed;
    cursor: not-allowed;
  }
}

button {
  height: 30px;
  line-height: 28px;
  padding: 0 20px;
  margin: 4px 8px 4px 0;
  background-color: white;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  @include sku-state-mixin;
}

.cart-btn {
  width: 200px;
  height: 50px;
  margin: 0 auto;
}

.el-dropdown-link {
  font-size: 16px;
}

.main-container-price {
  font-size: 24px;
  font-weight: bold;
  color: crimson;
  margin: 10px 0;
}

.main-container-title {
  font-size: 22px;
  font-weight: bold;
  color: black;
}

.main-container-table {
  width: 100%;
  min-height: 350px;
}

.main-container-carousel-img {
  max-width: 500px;
  max-height: 500px;
}

.main-container-carousel {
  max-width: 500px;
  border-radius: 10px;
}

.main-container {
  width: 80%;
  margin: 0 auto;
  margin-top: 20px;
}

.dropdown-card {
  width: 200px;
  display: inline-block;
  margin: 10px;
}

.main-container-table {
  display: block;
}
</style>